package ro.gateway.aida.servlet;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;

import javax.servlet.http.HttpServlet;

import ro.gateway.aida.admin.ActivityObjectsOptions;
import ro.gateway.aida.db.PersistenceManager;
import ro.gateway.aida.db.PersistenceToken;
import ro.gateway.aida.obj.db.SystemPropertyDB;


public class LoadAOOFServlet extends HttpServlet {

      public void init () {
            ActivityObjectsOptions options = ActivityObjectsOptions.getInstance();

            PersistenceToken token = PersistenceManager.tokenLookup( getServletContext() );
            try {
                  String properties = SystemPropertyDB.getManager( token )
                        .getProperty( "actoobjoptions" );
                  if ( properties != null ) {
                        options.loadFromString( properties );
                        return;
                  }
            } catch ( Exception ex ) {
                  ex.printStackTrace();
            }

//            try
//            {
//                  InputStream is = this.getServletContext().getResourceAsStream( "/WEB-INF/aoof.properties" );
//                  if ( is != null )
//                  {
//                        System.out.println( "Load AOOF: Found aoof.properties" );
//                        options.loadFromProperties( is );
//                        is.close();
//                        return;
//                  } else {
//                        System.out.println( "Load AOOF: aoof.properties not found" );
//                  }
//            }
//            catch ( IOException ioEx )
//            {
//                  ioEx.printStackTrace();
//            }

            // properties not there... so improvizez
            System.out.println( "Object properties file not found. Loading from Constants class" );
            try {
                  Class clasa = Class.forName( "ro.gateway.aida.admin.ActObjsOptsConst" );
                  Field[] fields = clasa.getDeclaredFields();
                  for ( int i = 0; i < fields.length; i++ ) {
                        if ( ( fields[ i ].getModifiers() & Modifier.STATIC ) != 0 ) {
                              Object obj = fields[ i ].get( null );
                              if ( obj instanceof String ) {
                                    String name = ( String ) obj;
                                    options.register( name );
                                    options.setEnabled( name, true );
                                    options.setMandatory( name, true );
//                                    System.out.println( "registered:" + name );
                              }
                        }
                  }
            } catch ( Exception ex ) {
                  ex.printStackTrace();
            }
      }
}
